﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Powerpi.Models;

namespace Powerpi.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult Index(string returnUrl = null)
        {

            return View(new LoginViewModel());
        }
        [HttpPost]
        public async Task<ActionResult> Index(LoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var file = System.IO.Path.Combine(Environment.CurrentDirectory, "Configs", "User");
                if (!System.IO.File.Exists(file))
                {
                    var usr = Newtonsoft.Json.JsonConvert.SerializeObject(model);
                    System.IO.File.WriteAllText(file, usr);
                }
                var user = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginViewModel>(System.IO.File.ReadAllText(file));
                if (user.Account == model.Account && user.Password == model.Password)
                {
                    var authpro = new AuthenticationProperties() { IsPersistent = true };
                    if (!authpro.IsPersistent)
                    {
                        authpro.IssuedUtc = DateTime.UtcNow;
                        authpro.ExpiresUtc = DateTime.UtcNow.AddMinutes(20);
                    }
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, GeneratePrincipal(model.Account), authpro);

                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("index", "home");
                    }
                    else
                    {
                        return Redirect(HttpUtility.UrlDecode(returnUrl));
                    }
                }
                else
                {
                    ViewBag.Message = "账号或密码错误";

                }
            }
            else
            {
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        ModelState.AddModelError("", item.Errors[0].ErrorMessage);
                        ViewBag.Message = item.Errors[0].ErrorMessage;
                    }
                }

            }
            return View(model);
        }

        [HttpGet]
        public ActionResult Password()
        {
            return View(new ModifyPwdViewModel());
        }
        [HttpPost]
        public ActionResult Password(ModifyPwdViewModel model)
        {
            if (ModelState.IsValid)
            {
                var file = System.IO.Path.Combine(Environment.CurrentDirectory, "Configs", "User");
                if (!System.IO.File.Exists(file))
                {
                    var usr = Newtonsoft.Json.JsonConvert.SerializeObject(model);
                    System.IO.File.WriteAllText(file, usr);
                }
                var user = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginViewModel>(System.IO.File.ReadAllText(file));
                if (user.Account == model.Account && user.Password == model.Password)
                {
                    if (model.NewPassword != model.ConfirmPassword)
                    {
                        ViewBag.Message = "两次密码不一致";
                    }
                    else
                    {
                        user.Password = model.NewPassword;
                        var usr = Newtonsoft.Json.JsonConvert.SerializeObject(user);
                        System.IO.File.WriteAllText(file, usr);
                        ViewBag.Message = "密码修改成功";
                    }
                }
                else
                {
                    ViewBag.Message = "账号或密码错误";

                }
            }
            else
            {
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        ModelState.AddModelError("", item.Errors[0].ErrorMessage);
                        ViewBag.Message = item.Errors[0].ErrorMessage;
                    }
                }

            }
            return View(model);
        }

        #region Private
        private ClaimsPrincipal GeneratePrincipal(string result)
        {
            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, result));
            var principal = new ClaimsPrincipal(identity);
            return principal;
        }
        #endregion
    }
}
